//配置baseUrl
const baseUrl = 'http://localhost:5000'

//json转params
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

//fetch封装
class http {
  //get方式
  get(url, data) {
    //生成token
    const token = window.sessionStorage.getItem('token')
    return new Promise((resolve, reject) => {
      fetch((baseUrl + url + '?' + obj2String(data)), {
        headers: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err))
    })
  }
  // post方式
  post(url, data) {
    //生成token
    const token = window.sessionStorage.getItem('token')
    return new Promise((resolve, reject) => {
      fetch(baseUrl + url, {
        method: 'POST',
        headers: {
          'Content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(data)
      })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err))
    })
  }
}
export default new http();